<template>
  <div class="pd-20">
    <el-input v-model="searchCondition" clearable class="w-200" placeholder="请输入关键词" @clear="handleQuey()"></el-input>
    <el-button type="primary"
               @click="handleQuey()">查 询
    </el-button>
    <el-button type="primary"
               @click="handleAdd()">新 增
    </el-button>


    <element-table class="mt-20"
                   :columns="columns"
                   :data="tableData"
                   v-loading="loading"
                   pager
                   :pageTotal="pageTotal"
                   :pageIndex="pageIndex"
                   :pageSize="pageSize"
                   @handleChangePage="handleChangePage">
      <template v-slot:option="{row}">
        <el-button type="primary"
                   @click="handleOption('edit', row)">编辑
        </el-button>
        <el-button type="danger"
                   @click="handleOption('del', row)">删除
        </el-button>
        <el-button type="warning"
                   @click="handleOption('config', row)">评分标准配置
        </el-button>
      </template>
    </element-table>


    <el-dialog :title="title"
               :visible.sync="showDialog"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               v-loading="loading"
               width="70%">
      <el-form :model="submitData"
               label-position="right"
               ref="formModelRef"
               :rules='formModelRules'
               label-width="150px">
        <el-form-item prop="scaleName" label="量表名称：">
          <el-input v-model="submitData.scaleName"
                    clearable
                    style="width: 380px"
                    placeholder="请输入量表名称"></el-input>
        </el-form-item>

        <el-form-item label="首次提交奖励：">
          <el-select v-model="submitData.awardId"
                     clearable
                     class="w-200"
                     placeholder="请选择">
            <el-option v-for="item in liangbiaoList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="量表指导语：">
          <el-input v-model="submitData.guidingWords"
                    clearable
                    style="width: 380px"
                    placeholder="请输入量表指导语"></el-input>
        </el-form-item>

        <el-form-item label="针对性别：">
          <el-select v-model="submitData.genderType"
                     clearable
                     class="w-200"
                     placeholder="请选择性别">
            <el-option v-for="item in sexList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="量表题目及答案：">
          <el-button type="primary" @click="handleAddQA">增加题目</el-button>
        </el-form-item>
        <el-form-item v-for="(item,index) in submitData.subjects" :key="index">
          <div style="display: flex;flex-direction: row;align-items: center">
            <el-upload :action="fileLogoUploadAction"
                       :max-size="fileMaxSize"
                       class="avatar-uploader"
                       :show-file-list="false"
                       :on-exceeded-size="showError"
                       :on-success="uploadLogoSuccess">
              <img v-if="item.imgUrl"
                   :src="item.imgUrl"
                   width="100px"
                   height="100px"
                   style="border-radius: 5%"
                   class="avatar">
              <i v-else
                 class="el-icon-plus avatar-uploader-icon" @click="handleChooseImg(index)"></i>
              <i v-if="item.imgUrl" @click.stop="handleDelImg(index)" class="del el-icon-error"></i>
            </el-upload>
            <p style="margin-left: 20px">题目{{ index + 1 }}:</p>
            <el-checkbox v-model="item.asCondition" :true-label="1" :false-label="0" style="margin-left: 25px">是否为条件
            </el-checkbox>

          </div>

          <el-input v-model="item.subjectName"
                    clearable
                    style="width: 380px"
                    placeholder="请输入题目"></el-input>
          <el-input v-model="item.sortNum"
                    clearable
                    style="width: 80px"
                    placeholder="排序"></el-input>
          <el-button type="primary" @click="handleAddOption(index)">增加选项</el-button>
          <el-button type="danger" @click="handleDelQA(index)">删除题目</el-button>
          <div v-for="(its,idx) in item.options" :key="idx" style="display: flex;flex-direction: row;margin-top: 20px">
            <el-input v-model="its.optionName"
                      clearable
                      style="width: 380px"
                      type="textarea"
                      placeholder="请输入选项"></el-input>
            <el-input v-model="its.optionScore"
                      clearable
                      style="width: 80px;margin-left: 5px"
                      placeholder="得分"></el-input>
            <el-button type="danger" @click="handleDelOption(index,idx)" style="margin-left: 5px">删除选项</el-button>
          </div>


        </el-form-item>


      </el-form>
      <p align="center">
        <el-button @click="showDialog=false"
                   type="info">取 消
        </el-button>
        <el-button type="primary"
                   v-prevent-re-click
                   @click="submitForm()">保 存
        </el-button>
      </p>

    </el-dialog>


    <el-dialog title="评分标准配置"
               :visible.sync="configDialog"
               v-loading="loading"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               width="70%">
      <el-tabs type="border-card" v-model="activiName">
        <el-tab-pane label="普通模式" :name="1">
          <el-form :model="configData"
                   ref="formModelRef"
                   label-width="110px">

            <el-form-item label="配置：">
              <el-button type="primary" @click="handleAddConfig">增 加</el-button>
            </el-form-item>

            <el-form-item v-for="(item,index) in configData.results" :key="index">
              <div style="display: flex;flex-direction: row;align-items: center">
                <el-input v-model="item.resultRank"
                          clearable
                          style="width: 160px;margin-right: 10px"
                          placeholder="请填写风险等级"/>

                <el-input v-model="item.result"
                          clearable
                          style="width: 160px"
                          placeholder="请填写结论"/>

                <el-select v-model="item.resultStatus"
                           clearable
                           style="width: 100px;margin-left: 10px;margin-right: 10px"
                           placeholder="状态">
                  <el-option v-for="item in configStatus"
                             :key="item.id"
                             :label="item.name"
                             :value="item.id">
                  </el-option>
                </el-select>
                <el-input v-model="item.firstNum"
                          clearable
                          placeholder="左边值"
                          style="width: 100px"/>
                <el-select v-model="item.firstCondition"
                           clearable
                           style="width: 100px;margin-left: 10px;margin-right: 10px"
                           placeholder="请选择">
                  <el-option v-for="item in fuhaoLeft"
                             :key="item.id"
                             :label="item.name"
                             :value="item.id">
                  </el-option>
                </el-select>
                <p>结果</p>
                <el-select v-model="item.secondCondition"
                           clearable
                           style="width: 100px;margin-left: 10px;margin-right: 10px"
                           :disabled="item.firstCondition==1"
                           placeholder="请选择">
                  <el-option v-for="item in fuhaoRight"
                             :key="item.id"
                             :label="item.name"
                             :value="item.id">
                  </el-option>
                </el-select>

                <el-input v-model="item.secondNum"
                          clearable
                          placeholder="右边值"
                          :disabled="item.firstCondition==1"
                          style="width: 100px"/>
                <el-button type="danger" style="margin-left: 10px" @click="handleDelConfig(index)">删 除</el-button>
              </div>
            </el-form-item>

          </el-form>
          <p align="center">
            <el-button @click="configDialog=false"
                       type="info">取 消
            </el-button>
            <el-button type="primary"
                       v-prevent-re-click
                       @click="submitConfig()">保 存
            </el-button>
          </p>

        </el-tab-pane>
        <el-tab-pane label="脑卒中危险评分" :name="2">
          <el-form :model="configData"
                   label-width="110px">

            <el-form-item label="脑卒中配置：">
              <el-button type="primary" @click="handleAddOldConfig">增 加</el-button>
            </el-form-item>

            <el-form-item v-for="(item,index) in updateConditionData.relationConditions" :key="index">
              <el-tag>条件{{ item.localId }}</el-tag>

              <el-row :gutter="15">
                <el-col :span="3">
                  <el-input v-model="item.firstNum"
                            clearable
                            placeholder="左边值"/>

                </el-col>
                <el-col :span="3">
                  <el-select v-model="item.firstCondition"
                             clearable
                             placeholder="请选择">
                    <el-option v-for="item in fuhaoLeft"
                               :key="item.id"
                               :label="item.name"
                               :value="item.id">
                    </el-option>
                  </el-select>

                </el-col>
                <el-col :span="3">
                  <el-input v-model="item.score"
                            disabled
                            placeholder="非条件题目得分"/>
                </el-col>
                <el-col :span="3">
                  <el-select v-model="item.secondCondition"
                             clearable
                             :disabled="item.firstCondition==1"
                             placeholder="请选择">
                    <el-option v-for="item in fuhaoRight"
                               :key="item.id"
                               :label="item.name"
                               :value="item.id">
                    </el-option>
                  </el-select>

                </el-col>
                <el-col :span="3">
                  <el-input v-model="item.secondNum"
                            clearable
                            placeholder="右边值"
                            :disabled="item.firstCondition==1"/>

                </el-col>
                <el-col :span="3">
                  <el-select v-model="item.relationConditionId"
                             clearable
                             @change="handleChange(index)"
                             placeholder="请选择合并条件题目">
                    <el-option v-for="item in subjectConditions"
                               :key="item.id"
                               :label="item.subjectName"
                               :value="item.id">
                    </el-option>
                  </el-select>

                </el-col>
                <el-col :span="3">
                  <el-select v-model="item.relationConditionOptionId"
                             clearable
                             placeholder="请选择条件题目选项">
                    <el-option v-for="its in item.conditionOptions"
                               :key="its.id"
                               :label="its.optionName"
                               :value="its.id">
                    </el-option>
                  </el-select>

                </el-col>
                <el-col :span="3">
                  <el-button type="danger" @click="handleDelOldConfig(index,item)">删 除
                  </el-button>
                </el-col>
              </el-row>

            </el-form-item>


            <el-form-item label="标准配置：">
              <el-button type="primary" @click="handleAddOldCondition">增 加</el-button>
            </el-form-item>

            <el-form-item v-for="(item,index) in updateConditionData.relationJudges" :key="index">
              <el-row :gutter="15">
                <el-col :span="4">
                  <el-input v-model="item.resultRank"
                            placeholder="请填写风险等级"
                            clearable/>
                </el-col>
                <el-col :span="4">
                  <el-input v-model="item.result"
                            placeholder="请填写结论"
                            clearable/>
                </el-col>
                <el-col :span="4">
                  <el-select v-model="item.resultStatus"
                             clearable
                             placeholder="请选择状态">
                    <el-option v-for="item in configStatus"
                               :key="item.id"
                               :label="item.name"
                               :value="item.id">
                    </el-option>
                  </el-select>

                </el-col>
                <el-col :span="3">
                  <el-select v-model="item.conditionIdList"
                             clearable
                             multiple
                             placeholder="请选择条件">
                    <el-option v-for="item in updateConditionData.relationConditions"
                               :key="item.localId"
                               :label="'条件'+item.localId"
                               :value="item.localId">
                    </el-option>
                  </el-select>

                </el-col>
                <el-col :span="3">
                  <el-select v-model="item.conditionType"
                             clearable
                             placeholder="条件关系">
                    <el-option v-for="item in guanxi"
                               :key="item.id"
                               :label="item.name"
                               :value="item.id">
                    </el-option>
                  </el-select>

                </el-col>
                <el-col :span="3">
                  <el-input v-model="item.judgeWords"
                            placeholder="请填写评分准则"
                            clearable/>
                </el-col>
                <el-col :span="3">
                  <el-button type="danger" @click="handleDelOldCondition(index)">删 除
                  </el-button>
                </el-col>
              </el-row>


            </el-form-item>
          </el-form>
          <p align="center" style="margin-top: 20px">
            <el-button @click="configDialog=false"
                       type="info">取 消
            </el-button>
            <el-button type="primary"
                       v-prevent-re-click
                       @click="submitOldConfig()">提 交
            </el-button>
          </p>

        </el-tab-pane>
      </el-tabs>

    </el-dialog>


  </div>
</template>

<script>
import ElementTable from '@/base/ElementTable'

export default {
  name: "liangbiaoList",
  data() {
    return {
      fileLogoUploadAction: this.api.file.upload,
      fileMaxSize: 1024 * 50,
      activiName: 1,
      imgIndex: 0,
      tableData: [],
      columns: [
        {
          label: '量表名称',
          prop: 'scaleName',
          align: "center"
        }, {
          label: '创建时间',
          prop: 'createTime',
          align: 'center',
          width: 200,
          formatter: (row, cellValue) => {
            return this.commonFunction.timestampFormat(new Date(row.createTime), 'yyyy-MM-dd hh:mm:ss')
          }
        }, {
          label: '操作',
          prop: 'option',
          align: 'center',
          isSlot: true,
          width: 450
        }
      ],
      loading: false,
      showDialog: false,
      configDialog: false,
      liangbiaoList: [],
      id: '',
      pageTotal: 0,
      pageIndex: 1,
      pageSize: 20,
      dataObj: {},
      list: [],
      fuhaoRight: [{
        name: '<=',
        id: 5
      }],
      fuhaoLeft: [
        {
          name: '=',
          id: 1
        }, {
          name: '<=',
          id: 5
        }],
      configStatus: [
        {
          name: '正常',
          id: 1
        },
        {
          name: '异常',
          id: 0
        },
      ],
      guanxi: [
        {
          name: '全部满足',
          id: 1
        },
        {
          name: '任一满足',
          id: 2
        }, {
          name: '满足任何两个',
          id: 3
        }],
      configData: {
        id: '',
        results: []
      },
      //老中卒条件
      obiitData: {
        list: []
      },
      //老卒中新增条件
      updateConditionData: {
        id: '',
        relationConditions: [],//条件列表
        relationJudges: [{
          conditionIdList: []
        }]//判断标准列表
      },
      defaultData: {
        id: '',
        genderType: 1,
        scaleName: '',
        guidingWords: '',
        awardId: '',
        awardType: '',
        subjects: []
      },
      submitData: {
        id: '',
        genderType: 1,
        scaleName: '',
        guidingWords: '',
        awardId: '',
        awardType: '',
        subjects: [
          {
            subjectName: '',
            sortNum: '',
            asCondition: 0,//是否为条件
            imgUrl: '',
            options: [
              {
                optionName: '',
                optionScore: '',
              }
            ]
          }
        ]
      },
      title: "新 增",
      sexList: [{name: '男女通用', id: 1}, {name: '男', id: 2}, {name: '女', id: 3}],
      subjectConditions: [],
      conditionOptions: [],
      num: 0,
      formModelRules: {
        scaleName: [
          {required: true, message: '请输入量表名称', trigger: 'blur'},
        ],
      },
      searchCondition: ''


    }
  },
  created() {
    this.getScaleAll()
    this.getHealthMapAwardList()
  },
  components: {
    'element-table': ElementTable
  },
  methods: {
    getScaleAll() {
      this.post(this.api.healthMap.getScaleAll, {
        pageIndex: this.pageIndex - 1,
        pageSize: this.pageSize,
        searchCondition: this.searchCondition
      }).then((res) => {
        if (res.data.code === '200') {
          this.tableData = res.data.object
          this.pageTotal = res.data.totalNum
        }
      })
    },
    //查询
    handleQuey() {
      this.pageIndex = 1
      this.getScaleAll()
    },
    handleAdd() {
      this.showDialog = true
      this.title = '新 增'
      this.submitData = {
        id: '',
        scaleName: '',
        guidingWords: '',
        awardId: '',
        awardType: '',
        subjects: []
      }
    },
    async handleOption(op, row) {
      switch (op) {
        case 'edit':
          this.showDialog = true
          this.title = '编 辑'
          this.submitData = {
            id: '',
            scaleName: '',
            guidingWords: '',
            awardId: '',
            awardType: '',
            subjects: []
          }
          this.getHealthMapScaleContent(row.id)
          break
        case 'del':
          this.$confirm('是否要确认?', '提示', {
            type: 'warning'
          }).then(() => {
            this.getHealthMapScaleDel(row.id)
          })
          break
        case 'config':
          this.configData.id = row.id
          this.configDialog = true
          this.configData.results = []
          this.updateConditionData.relationConditions = []
          this.updateConditionData.relationJudges = []

          this.activiName = row.judgeMode

          this.id = row.id
          this.getSubjectConditions()

          this.getHealthMapResult()
          this.getRelationDetail(row.id)
          break

      }
    },
    //确认配置
    submitConfig() {
      this.updateHealthMapResult()


    },
    submitOldConfig() {
      this.updateRelation()
    },
    //添加配置条件
    handleAddConfig() {
      var list = this.configData.results
      var data = {
        result: '',
        resultStatus: '',
        firstCondition: '',
        firstNum: '',
        secondCondition: '',
        secondNum: '',
        resultRank: '',
      }
      list.push(data)
    },
    //添加老卒中条件
    handleAddOldConfig() {
      var list = this.updateConditionData.relationConditions

      if (list.length > 0) {
        this.num = Math.max.apply(null, list.map(item => item.localId)) + 1
      } else {
        this.num = this.num + 1
      }

      var data = {
        firstCondition: '',
        firstNum: '',
        secondCondition: '',
        secondNum: '',
        relationConditionId: '',
        relationConditionOptionId: '',
        localId: this.num
      }
      list.push(data)

    },
    //添加老卒中配置
    handleAddOldCondition() {
      var list = this.updateConditionData.relationJudges
      var data = {
        result: '',
        resultStatus: '',
        conditionType: '',
        judgeWords: '',
        resultRank: '',
        conditionIdList: [],
      }
      list.push(data)
    },
    //删除老卒中配置
    handleDelOldCondition(index) {
      this.updateConditionData.relationJudges.splice(index, 1)
    },
    handleChange(index) {
      this.getConditionOptions(this.updateConditionData.relationConditions[index].relationConditionId, index)
      this.updateConditionData.relationConditions[index].relationConditionOptionId = ""
    },
    //查询老卒中详情
    getRelationDetail(id) {
      this.post(this.api.healthMap.getRelationDetail, {
        id: id
      }).then((res) => {
        if (res.data.code === '200') {
          this.updateConditionData.relationConditions = res.data.object.relationConditions
          this.updateConditionData.relationJudges = res.data.object.relationJudges
          //获取数组对象属性最大值
          if (res.data.object.relationConditions.length > 0) {
            this.num = Math.max.apply(null, res.data.object.relationConditions.map(item => item.localId))
          } else {
            this.num = res.data.object.relationConditions.length
          }

          //查询量表对应的答案
          this.updateConditionData.relationConditions.forEach((item, index) => {
            if (item.relationConditionId) {
              this.getConditionOptions(item.relationConditionId, index)
            }
          })
        }
      })
    },
    //查询带关联条件判断模式所有关联条件
    getSubjectConditions() {
      this.post(this.api.healthMap.getSubjectConditions, {
        scaleId: this.id
      }).then((res) => {
        if (res.data.code === '200') {
          this.subjectConditions = res.data.object

        }
      })
    },
    //查询带关联条件判断模式所有关联条件
    getConditionOptions(id, index) {
      this.post(this.api.healthMap.getConditionOptions, {
        subjectId: id
      }).then((res) => {
        if (res.data.code === '200') {
          this.updateConditionData.relationConditions[index].conditionOptions = res.data.object
          this.$forceUpdate()
        }
      })
    },
    //删除配置条件
    handleDelConfig(index) {
      this.configData.results.splice(index, 1)
    },
    //删除老卒中天剑
    handleDelOldConfig(index, item) {
      this.updateConditionData.relationConditions.splice(index, 1)


      // this.updateConditionData.relationJudges.forEach(item => item.conditionIdList = [])
      this.updateConditionData.relationJudges.forEach(its => {
        its.conditionIdList.forEach(itemid => {
          if (item.localId == itemid) {
            its.conditionIdList = its.conditionIdList.filter(f => f != itemid)
          }
        })
      })
    },
    //获取奖励列表
    getHealthMapAwardList() {
      this.post(this.api.healthMap.getHealthMapAwardList).then((res) => {
        if (res.data.code === '200') {
          this.liangbiaoList = res.data.object
        }
      })
    },
    //新增或修改量表
    updateHealthMapScale() {
      this.loading = true
      this.post(this.api.healthMap.updateHealthMapScale, this.submitData).then((res) => {
        this.loading = false
        if (res.data.code === '200') {
          this.$message.success('操作成功')
          this.showDialog = false
          this.getScaleAll()
        }
      })
    },
    //获取量表详情
    getHealthMapScaleContent(id) {
      this.post(this.api.healthMap.getHealthMapScaleContent, {
        id: id
      }).then((res) => {
        if (res.data.code === '200') {
          this.submitData = Object.assign(this.defaultData, res.data.object)
        }
      })
    },
    //删除量表
    getHealthMapScaleDel(id) {
      this.post(this.api.healthMap.getHealthMapScaleDel, {
        id: id
      }).then((res) => {
        if (res.data.code === '200') {
          this.$message.success('操作成功')
          this.getScaleAll()
        }
      })
    },
    //配置
    updateHealthMapResult() {
      this.loading = true
      this.post(this.api.healthMap.updateHealthMapResult, this.configData).then((res) => {
        this.loading = false
        if (res.data.code === '200') {
          this.configDialog = false
          this.$message.success('操作成功')
          this.getScaleAll()
        }
      })
    },
    //保存老卒中
    updateRelation() {
      this.updateConditionData.id = this.id
      this.loading = true
      this.post(this.api.healthMap.updateRelation, this.updateConditionData).then((res) => {
        this.loading = false
        if (res.data.code === '200') {
          this.configDialog = false
          this.$message.success('操作成功')
          this.getScaleAll()
        }
      })
    },
    //获取配置
    getHealthMapResult() {
      this.post(this.api.healthMap.getHealthMapResult, {
        id: this.configData.id
      }).then((res) => {
        if (res.data.code === '200') {
          this.configData.results = res.data.object
        }
      })
    },
    //增加题目
    handleAddQA() {
      let bean = {
        subjectName: '',
        sortNum: '',
        asCondition: 0,
        imgUrl: '',
        options: []
      }
      this.submitData.subjects.push(bean)


    },

    //增加选项
    handleAddOption(index) {
      var bean = {
        optionName: '',
        optionScore: ''
      }
      this.submitData.subjects[index].options.push(bean)
    },
    //删除题目
    handleDelQA(index) {
      this.submitData.subjects.splice(index, 1)
    },
    //删除选项
    handleDelOption(index, idx) {
      this.submitData.subjects[index].options.splice(idx, 1)
    },
    showError(file, fileList) {
      this.$Notice.warning({
        title: '文件大小超限',
        desc: "文件  " + file.name + " 太大，上传文件大小不能超过100M."
      });
    },
    //上传成功
    uploadLogoSuccess(res) {
      if (res.code === '200') {
        this.$message.success('上传成功');
        this.$set(this.submitData.subjects[this.imgIndex], 'imgUrl', res.object[0])
        // this.submitData.subjects[this.imgIndex].imgUrl = res.object[0]
      } else {
        this.$message.error('上传失败');
      }
    },
    //添加图片
    handleChooseImg(index) {
      this.imgIndex = index
    },
    //清除图片
    handleDelImg(index) {
      this.submitData.subjects[index].imgUrl = ''
    },
    //提交
    submitForm() {
      this.$refs.formModelRef.validate(async (valid) => {
        if (valid) {
          let awardId = this.submitData.awardId;
          if (awardId) {
            this.submitData.awardType = this.liangbiaoList.find(item => item.id === awardId).type
          }
          this.updateHealthMapScale()
        }
      })


    },
    // 分页
    handleChangePage(page) {
      this.pageIndex = page;
      this.getScaleAll();
    },
    // 时间转换
    formatterDate(row) {
      return this.commonFunction.timestampFormat(new Date(row.createTime), 'yyyy-MM-dd hh:mm')
    }
  },
}
</script>

<style scoped lang="scss">
.avatar-uploader {
  /deep/ .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;

    .del {
      position: absolute;
      z-index: 99;
      top: 0;
      right: 0;
      font-size: 16px;
      color: #f00;
    }

    .avatar {
      width: 98px !important;
      height: 98px !important;
      display: block;
    }

    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 98px !important;
      height: 98px !important;
      line-height: 98px !important;
      text-align: center;
    }

    &.el-upload--picture-card {
      width: 98px !important;
      height: 98px !important;
      line-height: 98px !important;
    }

    &:hover {
      border-color: #409eff;
    }
  }

  /deep/ .el-upload-list--picture-card {
    .el-upload-list__item {
      width: 98px;
      height: 98px;
    }
  }
}
</style>
